package cn.xy.third.sms.impl;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.extra.mail.MailAccount;
import cn.hutool.extra.mail.MailUtil;
import cn.xy.third.sms.EmailService;
import cn.xy.third.sms.email.EmailConfig;
import cn.xy.third.sms.email.EmailTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * 邮件发送实现
 *
 *  @author xy
 */
@Slf4j
@Service
public class EmailServiceImpl implements EmailService {

    @Autowired
    private EmailConfig emailConfig;

    private static MailAccount account;

    private static MailAccount getAccount(EmailConfig config) {
        if (account != null) {
            return account;
        }
        account = new MailAccount();
        account.setHost(config.getHost());
        account.setPort(config.getPort());
        account.setFrom(config.getForm());
        account.setUser(config.getUser());
        account.setPass(config.getPass());
        account.setStarttlsEnable(true);
        return account;
    }

    @Override
    public boolean sendEmail(String email, String title, String body) {
        try {
            MailAccount mailAccount = getAccount(emailConfig);
            String massageId = MailUtil.send(mailAccount, email, title, body, true);
            return CharSequenceUtil.isNotEmpty(massageId);
        } catch (Exception e) {
            log.error("邮件发送失败，email：{}， title： {}", email, title);
            log.error("send email error: {}", e.getMessage());
            return false;
        }
    }

    @Override
    public boolean sendEmail(String email, String templateName, Map<String, String> templateParam) {
        EmailTemplate template = emailConfig.getTemplateByName(templateName);
        if (template == null || CharSequenceUtil.isEmpty(template.getTemplateTitle())
                || CharSequenceUtil.isEmpty(template.getTemplateContent())) {
            log.error("邮件发送失败，邮箱配置异常，email：{}， templateName： {}", email, templateName);
            return false;
        }
        String body = template.toBody(templateParam);
        return this.sendEmail(email, template.getTemplateTitle(), body);
    }

}
